package general;

/**
 * Class providing general bit manipulation methods.
 */
public class Bit {
	
	/**
	 * Transforms the given byte array to long integer
	 * @param bytes The transformed byte array
	 * @return The resulting long integer
	 */
	public static long toLong(byte[] bytes) {
		long n = 0;
		if (bytes.length == 8) {
			n |= ((long)(bytes[0]   & 0xff) << 56) ;
			n |= ((long)(bytes[1]   & 0xff) << 48) ;
			n |= ((long)(bytes[2]   & 0xff) << 40) ;
			n |= ((long)(bytes[3]   & 0xff) << 32) ;
			n |= ((long)(bytes[4]   & 0xff) << 24) ;
			n |= ((long)(bytes[5]   & 0xff) << 16) ;
			n |= ((long)(bytes[6]   & 0xff) << 8) ;
			n |= ((long)(bytes[7]   & 0xff)) ;
        } else {
			/**
			 * Invalid array size
			 */
		}
		return n;
	}
	
	/**
	 * Transforms the given byte array to integer
	 * @param bytes The transformed byte array
	 * @return The resulting integer
	 */
	public static int toInt(byte[] bytes) {
		int n = 0;
		if (bytes.length == 4) {
			n |= ((bytes[0]   & 0xff) << 24); 
			n |= ((bytes[1]   & 0xff) << 16); 
			n |= ((bytes[2]   & 0xff) << 8); 
			n |= ((bytes[3]   & 0xff)); 
			} else {
			/**
			 * Invalid array size
			 */
		}
		return n;
	}
	
	/**
	 * Transforms the given long integer to byte array
	 * @param n The transformed long integer
	 * @return The resulting byte array
	 */
	public static byte[] toByteArray(long n) {
		byte[] bytes = new byte[8];
		bytes[0]   = (byte)(0xff & (n >> 56));
	    bytes[1] = (byte)(0xff & (n >> 48));
	    bytes[2] = (byte)(0xff & (n >> 40));
	    bytes[3] = (byte)(0xff & (n >> 32));
	    bytes[4] = (byte)(0xff & (n >> 24));
	    bytes[5] = (byte)(0xff & (n >> 16));
	    bytes[6] = (byte)(0xff & (n >> 8));
	    bytes[7] = (byte)(0xff & n);
	    return bytes;
		
	}
	
	/**
	 * Transforms the given integer to byte array
	 * @param n The transformed integer
	 * @return The resulting byte array
	 */
	public static byte[] toByteArray(int n) {
		byte[] bytes = new byte[4];
		
		bytes[0] = (byte)((n >> 24) & 0xff);
		bytes[1] = (byte)((n >> 16) & 0xff);
		bytes[2] = (byte)((n >> 8) & 0xff);
		bytes[3] = (byte)((n) & 0xff);
		return bytes;
	}
	
}